<?php


namespace App\Http\observer;


use App\Engine\BaseCommon;
use App\Models\AroundEnvironment;
use App\Models\Sys;
use Illuminate\Support\Facades\Cache;
use App\Models\Image as ImageModel;
use Illuminate\Support\Facades\Log;

class AroundEnvironmentObserve
{

    public function updating(AroundEnvironment $environment)
    {
        $old_qedit=ImageModel::where("id",$environment["id"])->first();
        $qedit=(new BaseCommon())->getImgs($old_qedit["content"],0);
        if($qedit){
            Cache::put("around_environment_qedit",$qedit);
        }

        $background=$old_qedit["background"];
        Cache::put("around_environment_background",$background);
    }

    public function updated(AroundEnvironment $environment)
    {
        $background=Cache::get("around_environment_background");
        $qedit=Cache::get("around_environment_qedit");
        $new_qedit=(new BaseCommon())->getImgs($environment->content);
        Cache::forget("around_environment_background");
        Cache::forget("around_environment_qedit");
        if ($background&&$background!=$environment->background){

            $image=ImageModel::where("url",$background)->first();
            if ($image){
                ImageModel::find($image["id"])->delete();
            }
        }

        if ($qedit&&$new_qedit!=$qedit){
            $oss_address=Sys::getValue("oss_address");
            $qedit=str_replace($oss_address,"",$qedit);
            Log::error($qedit);
            $image=ImageModel::where("url",$qedit)->first();
            Log::error($image);
            if ($image){
                ImageModel::find($image["id"])->delete();
            }
        }

    }

    public function deleted(AroundEnvironment $environment)
    {
        $image=ImageModel::where("url",$environment->background)->first();
        if ($image){
            ImageModel::find($image["id"])->delete();
        }

        $qedit=(new BaseCommon())->getImgs($environment["content"],0);
        $oss_address=Sys::getValue("oss_address");
        $qedit=str_replace($oss_address,"",$qedit);
        $image=ImageModel::where("url",$qedit)->first();
        if ($image){
            ImageModel::find($image["id"])->delete();
        }
    }
}
